package org.gten.gegedexin.service;

import com.alibaba.fastjson.JSONObject;
import org.gten.gegedexin.pojo.AtInfoPojo;
import org.gten.gegedexin.pojo.MailInfoPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import static org.gten.gegedexin.service.ReceiveFile.FILEPATH;

@Service
public class ReadMail {
    @Autowired
    AtInfoServiceImpl atInfoService;
    @Autowired
    MailInfoServiceImpl mailInfoService;

    public JSONObject readmail(String mailId){
        //  设置邮件为已读
        if(mailInfoService.getMailInfoById(Integer.parseInt(mailId)).get(0).getIsRead()==0)
            mailInfoService.setRead(Integer.parseInt(mailId));
        MailInfoPojo mail = mailInfoService.getMailInfoById(Integer.parseInt(mailId)).get(0);
        JSONObject json = new JSONObject();
        File mailPath = new File(FILEPATH+"resources/text/"+mailId+".txt");
        BufferedReader reader = null;
        String temp = null;
        String text = new String();
        //  读入发件人和主题
        json.put("sender",mail.getSender());
        json.put("title",mail.getHeader());
        //  读入正文
        try{
            reader = new BufferedReader(new FileReader(mailPath));
            //  读入正文
            while((temp=reader.readLine())!=null)
                text = text + temp + '\n';

            json.put("text",text);

        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            if(reader!=null){
            try{
                reader.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
        //  附件列表
//        json.put("appendixNum",fileList.size());
//        for(AtInfoPojo file:fileList){
//            json.put("appendix"+Integer.toString(i),file.getName());
//            i++;
//        }

        //  读入附件
        List<AtInfoPojo> fileList = atInfoService.getAtInfoById(Integer.parseInt(mailId));
        switch (fileList.size()){
            case 0:
                json.put("appendix0",null);
                json.put("appendix1",null);
                break;
            case 1:
                json.put("appendix0",fileList.get(0).getName());
                json.put("appendix1",null);
                break;
            case 2:
                json.put("appendix0",fileList.get(0).getName());
                json.put("appendix1",fileList.get(1).getName());
                break;
            default:
                json.put("appendix0",null);
                json.put("appendix1",null);
                break;
        }
        return json;
    }
}
